package org.aceor.mddal.gateway.router.handler;

import org.aceor.mddal.common.sqlparser.result.context.ConditionContext;
import org.aceor.mddal.common.sqlparser.result.context.RouteContext;
import org.aceor.mddal.common.sqlparser.result.context.ShardingContext;
import org.aceor.mddal.common.sqlparser.result.object.Column;
import org.aceor.mddal.gateway.executor.ExecuteContext;
import org.aceor.mddal.gateway.router.RouteHelper;

import java.util.Set;

import static org.aceor.mddal.common.utils.CommonUtil.print;

/**
 * Created by lxue on 16/4/14.
 */
public class JustDBShardingRouteHandler implements RouteHandler{
    @Override
    public ExecuteContext route(RouteHandlerParam param) {
        ExecuteContext executeContext = new ExecuteContext();

        ConditionContext conditionContext = param.sqlParsedResult.conditionContext;
        RouteContext routeContext = param.sqlParsedResult.routeContext;
        ShardingContext shardingContext = param.sqlParsedResult.shardingContext;

        Column column = new Column(
                RouteHelper.findTable(routeContext, shardingContext.logicTableName),
                shardingContext.dbShardingColumn);

        print(JustDBShardingRouteHandler.class, "db-column:" + column);
        Set<Object> values = RouteHelper.getAcceptableValues(
                conditionContext.getConditionMap().get(column),
                shardingContext.dbShardingFunction);
        RouteHelper.setExecuteSqlMapWhenSingleTbOrDbSharding(
                executeContext,
                column,
                values,
                shardingContext,
                routeContext.getSqlBuilder(),
                param.args,
                null);
        return executeContext;
    }
}
